/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.mobiubiq.directory.client.frame;

import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;
import org.kalmeo.kuix.core.Kuix;
import org.mobiubiq.directory.client.KuixClient;
import org.mobiubiq.directory.client.data.Bookmark;
import org.mobiubiq.directory.client.data.BookmarksDataProvider;
import org.mobiubiq.directory.client.object.AbstractObject;
import org.mobiubiq.directory.service.DirectoryService;
import org.mobiubiq.directory.service.DirectoryServiceDao;
import org.mobiubiq.directory.service.ServiceException;

/**
 *
 * @author Marnix Renne
 */
public class BookmarksEdit extends DataProviderBaseFrame {
    public static final String PROTOCOL = "bookmark";
    private BookmarksDataProvider bookmarksDataProvider;
    private String oldTitle;
    
    public BookmarksEdit(BookmarksDataProvider bookmarksDataProvider) {
        this(bookmarksDataProvider, new Bookmark(null));
    }

    public BookmarksEdit(BookmarksDataProvider bookmarksDataProvider, Bookmark bookmark) {
        super("bookmarks-edit.xml", bookmark);
        this.bookmarksDataProvider = bookmarksDataProvider;
        oldTitle = bookmark.getTitle();
    }

    public boolean onMessage(Object identifier, Object[] arguments) {
        if (super.onMessage(identifier, arguments)) {
            if ("save".equals(identifier)) {
                Bookmark bookmark = (Bookmark) getDataProvider();
                bookmark.setTitle((String)arguments[0]);
//                bookmark.setUrl((String)arguments[1]);
                try {
                    if(bookmark.getRecordId() > -1) {
                        bookmarksDataProvider.updateBookmark(bookmark);
                    } else {
                        bookmarksDataProvider.addBookmark(bookmark);
                    }
                    String newTitle = bookmark.getTitle();
                    if(newTitle != null && !newTitle.equals(oldTitle)) { // Object does not have a title yet, add it to service directory
                        AbstractObject abstractObject = bookmark.getObject();
                        if(abstractObject != null) {
                            DirectoryServiceDao directoryServiceDao = DirectoryService.getInstance(KuixClient.getDefault());
                            directoryServiceDao.setOrUpdateTitle(abstractObject, bookmark.getTitle(), "");
                        }
                    }
                } catch (RecordStoreNotOpenException ex) {
                    Kuix.alert(ex);
                } catch (RecordStoreException ex) {
                    Kuix.alert(ex);
                } catch (ServiceException ex) {
                    Kuix.alert(ex);
                }
                return super.onMessage("back", arguments);
            }
        } else {
            return false;
        }
        return true;
    }
}
